const app = getApp()
let qCloud = require("../../index.js");

Page({
    /** 页面的初始数据 */
    data: {
        imgPath: qCloud.config.STATIC_IMAGE_PATH,
        produceTaskId: 0, // 生产任务ID
        produceTaskCode: "", // 生产任务编号==款号
        produceTaskBedNo: "", // 生产任务床号
        produceTaskName: "", // 生产任务名称=="款号-床号"
        produceTotal: 0, // 生产数量
        unitPrice: 0, // 单价
        totalPrice: 0, // 总价
        startTime: "", // 开始时间
        deliveryTime: "", // 交货时间
        wagesModel: 1, // 工资模式
        wagesMonth: "", // 工资月份
        switchDay: 1, // 月切日期
        departmentName: "", // 部门名称
        specsTypeList: [], // 尺码类型列表
        specsTypeTitle: "", // 尺码类型
        processList: [], // 工序列表
        technologicalRequirements: "", // 工艺要求
        imageUrl: "",
        qrImageUrl: "",
        tabIndex: 1, // 页签坐标: 1-生产中; 2-已完成; 3-生产日报表;

        // 头部统计
        produceStatistics: {
            produceTaskId: null,
            produceTaskName: "",
            singleTotalPrice: 0.00,
            allTotalPrice: 0.00,
            upcountTotalPrice: 0.00,
        },

        showModalStatus: false,
        taskProcessList: [],

        staffList: [],
        searchStaffList: [],
        report: false

    },

    /** 生命周期函数--监听页面加载 */
    onLoad: function (options) {
        this.getUserInfo();
        this.getPermission();

        this.setData({
            produceTaskId: options.produceTaskId
        });
        if (this.data.tabIndex == 1) {
            this.queryProduceTaskDetails();
        }
    },

    onPullDownRefresh: function (){
        this.getUserInfo();
        this.getPermission();
    },

    getUserInfo: function () {
        let self = this;
        app.fetchApis(self, qCloud.api.getInfo, {}, "GET", function (e) {
            if (e.data.code == 200) {
                qCloud.session.setPermi(e.data.permissions);
                qCloud.session.setRole(e.data.role);
                qCloud.session.setUser(e.data.user);
            }
        });
    },

    getPermission: function () {
        let self = this;
        let permission = qCloud.session.getPermi();
        if (permission && permission.length > 0) {
            if (permission.indexOf("apc:produce:report") != -1) {
                self.setData({
                    report: true
                });
            } else {
                self.setData({
                    report: false
                });
            }
        } else {
            self.setData({
                report: false
            })
        }
    },

    // 顶部菜单选择
    tabClick(e) {
        let self = this;
        let tabIndex = e.currentTarget.dataset.index;
        self.setData({
            tabIndex: tabIndex // 页签坐标: 1-生产中; 2-已完成; 3-生产日报表;
        });

        if (self.data.tabIndex == 1) {
            self.queryProduceTaskDetails();
        }

        if (self.data.tabIndex == 2) {
            self.queryTaskProcessStatistic();
            self.queryTaskProcessWorkReportList();
        }
    },

    /** 查询生产任务详情 */
    queryProduceTaskDetails() {
        let self = this;
        let params = {
            produceTaskId: self.data.produceTaskId
        }
        app.fetchApis(self, qCloud.api.producetask_queryProduceTaskDetails, params, "POST", function (e) {
            let result = e.data;
            if (result.code == 200) {
                let data = result.data;
                self.setData({
                    produceTaskCode: data.produceTaskCode, // 生产任务编号==款号
                    produceTaskBedNo: data.produceTaskBedNo, // 生产任务床号
                    produceTaskName: data.produceTaskName, // 生产任务名称=="款号-床号"
                    produceTotal: data.produceTotal, // 生产数量
                    unitPrice: data.unitPrice, // 单价
                    totalPrice: data.totalPrice, // 总价
                    startTime: data.startTime, // 开始时间
                    deliveryTime: data.deliveryTime, // 交货时间
                    wagesModel: data.wagesModel, // 工资模式
                    wagesMonth: data.wagesMonth, // 工资月份
                    switchDay: data.switchDay, // 月切日期
                    departmentName: data.departmentName, // 部门名称
                    technologicalRequirements: data.technologicalRequirements, // 工艺要求
                    imageId: data.imageId, // 图片
                    qrImageId: data.qrImageId
                });

                // 获取图片信息
                if (data.imageId != null && data.imageId != "") {
                    self.getFilesUrl(data.imageId, 1);
                }

                if (data.qrImageId != null && data.qrImageId != "") {
                    self.getFilesUrl(data.qrImageId, 2);
                }

                // 转换尺码类型列表
                self.convertSpecsTypeList(data.produceTaskSpecsList);
                // 转换尺码类型
                self.convertSpecsTypeTitle(data.specsType);
                // 转换工序列表
                self.convertProcessList(data.produceTaskProcessList);
            }
        });
    },

    // 获取图片信息 1=工序 2=二维码
    getFilesUrl: function (imageId, type) {
        let self = this;
        let params = {
            filesId: imageId
        }
        app.fetchApis(self, qCloud.api.getFileUrl, params, "GET", function (e) {
            let result = e.data;
            if (result.code == 200) {
                let data = result.data;
                if (type == 1) {
                    self.setData({
                        imageUrl: data.filesUrl,
                    });
                }
                if (type == 2) {
                    self.setData({
                        qrImageUrl: data.filesUrl,
                    });
                }
            }
        });
    },

    // 转换尺码类型列表
    convertSpecsTypeList(produceTaskSpecsList) {
        let self = this;
        let specsTypeList = [];
        let colourIndex = [];
        for (let i = 0; i < produceTaskSpecsList.length; i++) {
            let produceTaskSpecs = produceTaskSpecsList[i];
            if (colourIndex.length > 0) {
                let ci = -1;
                for (let j = 0; j < colourIndex.length; j++) {
                    if (produceTaskSpecs.colour == colourIndex[j]) {
                        ci = j;
                        break;
                    }
                }

                if (ci == -1) {
                    colourIndex.push(produceTaskSpecs.colour);

                    let specsList = [{
                        specs: produceTaskSpecs.specs,
                        specsTotal: produceTaskSpecs.specsTotal,
                    }];
                    let specsTypeInfo = {
                        colour: produceTaskSpecs.colour,
                        specsList: specsList
                    };
                    specsTypeList.push(specsTypeInfo);
                } else {
                    let specsInfo = {
                        specs: produceTaskSpecs.specs,
                        specsTotal: produceTaskSpecs.specsTotal,
                    };
                    specsTypeList[ci]["specsList"].push(specsInfo);
                }
            } else {
                colourIndex.push(produceTaskSpecs.colour);

                let specsList = [{
                    specs: produceTaskSpecs.specs,
                    specsTotal: produceTaskSpecs.specsTotal,
                }];
                let specsTypeInfo = {
                    colour: produceTaskSpecs.colour,
                    specsList: specsList
                };
                specsTypeList.push(specsTypeInfo);
            }
        }

        self.setData({
            specsTypeList: specsTypeList // 尺码类型列表
        });
    },

    // 转换尺码类型
    convertSpecsTypeTitle(specsType) {
        let self = this;

        let specsTypeTitle = "";
        if (specsType == "SML") {
            specsTypeTitle = "SML尺码";
        } else if (specsType == "NS") {
            specsTypeTitle = "数字尺码";
        } else if (specsType == "CS") {
            specsTypeTitle = "自定义尺码";
        }
        self.setData({
            specsTypeTitle: specsTypeTitle
        });
    },

    // 转换工序列表
    convertProcessList(produceTaskProcessList) {
        let self = this;
        let processList = [];
        for (let i = 0; i < produceTaskProcessList.length; i++) {
            let produceTaskProcess = produceTaskProcessList[i];
            let processInfo = {
                processName: produceTaskProcess.processName,
                processTotal: produceTaskProcess.processTotal,
                unitPrice: produceTaskProcess.unitPrice,
            };
            processList.push(processInfo);
        }

        self.setData({
            processList: processList // 工序列表
        });
    },

    // 工序单价详情
    queryTaskProcessStatistic() {
        let self = this;
        let params = {
            produceTaskId: self.data.produceTaskId
        }
        app.fetchApis(self, qCloud.api.workreport_queryTaskProcessStatistic, params, "POST", function (e) {
            if (e.data.code == 200) {
                self.setData({
                    produceStatistics: e.data.data
                });
            }
        });
    },

    // 工序单价详情列表
    queryTaskProcessWorkReportList() {
        let self = this;
        let params = {
            produceTaskId: self.data.produceTaskId
        }
        app.fetchApis(self, qCloud.api.workreport_queryTaskProcessWorkReportList, params, "POST", function (e) {
            if (e.data.code == 200) {
                self.setData({
                    taskProcessList: e.data.data.taskProcessList,
                    staffList: e.data.data.staffList
                });
            }
        });
    },

    processTab: function (e) {
        let index = e.currentTarget.dataset.index;
        // 获取操作对象
        let taskProcessList = this.data.taskProcessList;
        if (taskProcessList[index].produceArrowRight) {
            taskProcessList[index].produceArrowRight = false;
        } else {
            taskProcessList[index].produceArrowRight = true;
        }

        this.setData({
            taskProcessList: taskProcessList
        })
    },

    changeWorkerName: function (e) {
        let parent = e.currentTarget.dataset.parent;
        let index = e.currentTarget.dataset.index;

        let taskProcessList = this.data.taskProcessList;
        let staffUpcountList = taskProcessList[parent].staffUpcountList;

        let searchStaffList = [];
        this.data.searchStaffList = [];
        for (let i = 0; i < this.data.staffList.length; i++) {
            let staff_0 = this.data.staffList[i];

            let flag = false;
            for (let j = 0; j < staffUpcountList.length; j++) {
                let staff_1 = staffUpcountList[j];
                if (staff_0.workerId == staff_1.workerId && !staff_1.deletedMark) {
                    flag = true;
                    break;
                }
            }

            if (!flag) {
                searchStaffList.push({
                    parentIndex: parent,
                    staffIndex: index,
                    workerId: staff_0.workerId,
                    workerName: staff_0.workerName
                })
            }
        }

        this.setData({
            searchStaffList: searchStaffList,
            showModalStatus: true
        })
    },

    submitTotalInput: function (e) {
        let index = e.currentTarget.dataset.index;
        let parent = e.currentTarget.dataset.parent;
        let inputValue = e.detail.value;

        // 获取操作对象
        let taskProcessList = this.data.taskProcessList;
        let processSubmitTotal = 0;
        for (let i = 0; i < taskProcessList[parent].staffUpcountList.length; i++) {
            if (i == index) {
                inputValue = inputValue == "" ? 0 : Number.parseInt(inputValue);
                taskProcessList[parent].staffUpcountList[i].submitTotal = inputValue;
                processSubmitTotal = processSubmitTotal + Number.parseInt(inputValue);
            } else {
                processSubmitTotal = processSubmitTotal + Number.parseInt(taskProcessList[parent].staffUpcountList[i].submitTotal);
            }
        }
        taskProcessList[parent].processSubmitTotal = processSubmitTotal;
        this.setData({
            taskProcessList: taskProcessList
        })
    },

    deleteStaffUpCount: function (e) {
        let index = e.currentTarget.dataset.index;
        let parent = e.currentTarget.dataset.parent;

        // 获取操作对象
        let taskProcessList = this.data.taskProcessList;
        if (taskProcessList[parent].staffUpcountList[index].workerUpcountId == null) {
            taskProcessList[parent].staffUpcountList.splice(index, 1);
        } else {
            taskProcessList[parent].staffUpcountList[index].deletedMark = true;
        }

        this.setData({
            taskProcessList: taskProcessList
        })
    },

    addStaffUpCount: function (e) {
        let parent = e.currentTarget.dataset.parent;

        // 获取操作对象
        let taskProcessList = this.data.taskProcessList;

        taskProcessList[parent].staffUpcountList.push({
            approvalQuantity: 0,
            deletedMark: false,
            modifyStaffMark: true,
            modifyMark: true,
            produceTaskId: Number.parseInt(this.data.produceTaskId),
            produceTaskProcessId: taskProcessList[parent].produceTaskProcessId,
            settleSalary: "0",
            submitTime: qCloud.util.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}'),
            submitTotal: 0,
            throughQuantity: 0,
            unitPrice: taskProcessList[parent].unitPrice,
            workerId: null,
            workerName: '',
            workerUpcountId: null
        })

        this.setData({
            taskProcessList: taskProcessList
        })
    },

    cancelProcessTab(e) {
        this.queryTaskProcessStatistic();
        this.queryTaskProcessWorkReportList();
    },

    saveProcessTab: function (e) {
        let self = this;
        let parent = e.currentTarget.dataset.parent;
        // 获取操作对象
        let taskProcessList = this.data.taskProcessList;
        let staffUpcountList = [];

        for (let i = 0; i < taskProcessList[parent].staffUpcountList.length; i++) {
            let staff = taskProcessList[parent].staffUpcountList[i];
            staffUpcountList.push({
                workerUpcountId: staff.workerUpcountId,
                workerId: staff.workerId,
                workerName: staff.workerName,
                submitTotal: staff.submitTotal,
                deletedMark: staff.deletedMark
            })
        }

        let params = {
            produceTaskId: Number.parseInt(this.data.produceTaskId),
            produceTaskProcessId: taskProcessList[parent].produceTaskProcessId,
            staffUpcountList: staffUpcountList
        }

        app.fetchApis(self, qCloud.api.workreport_submitTaskProcessWorkReport, params, "POST", function (e) {
            if (e.data.code == 200) {
                wx.showToast({
                    title: '上数成功',
                    icon: "success"
                })
                self.queryTaskProcessStatistic();
                self.queryTaskProcessWorkReportList();
            } else {
                wx.showToast({
                    title: e.data.msg,
                    icon: 'error'
                })
            }
        });
    },

    hideStaffModal: function (e) {
        let animation = wx.createAnimation({
            duration: 200,
            timingFunction: "linear",
            delay: 0
        });
        this.animation = animation;
        animation.translateY(300).step();
        this.setData({
            animationData: animation.export(),
        });
        setTimeout(function () {
            animation.translateY(0).step();
            this.setData({
                animationData: animation.export(),
                searchStaffList: [],
                showModalStatus: false
            })
        }.bind(this), 200);
    },

    searchWorkerNameInput: function (e) {
        let self = this;
        let staffList = self.data.staffList;
        if (e.detail.value === '') {
            self.setData({
                searchStaffList: []
            })
        } else {
            let searchStaffList = [];
            for (let i = 0; i < staffList.length; i++) {
                let staff = staffList[i];
                if (staff.workerName.indexOf(e.detail.value) != -1) {
                    searchStaffList.push({
                        parentIndex: null,
                        staffIndex: null,
                        workerId: staff.workerId,
                        workerName: staff.workerName
                    });
                }
            }
            self.setData({
                searchStaffList: searchStaffList
            })
        }
    },

    // 确认选择
    confirmStaff(e) {
        let index = e.currentTarget.dataset.index;
        let parent = e.currentTarget.dataset.parent;
        let staff = e.currentTarget.dataset.staff;

        // 获取操作对象
        let taskProcessList = this.data.taskProcessList;
        taskProcessList[parent].staffUpcountList[staff].workerId = this.data.searchStaffList[index].workerId;
        taskProcessList[parent].staffUpcountList[staff].workerName = this.data.searchStaffList[index].workerName;

        this.setData({
            taskProcessList: taskProcessList,
            showModalStatus: false
        })
    },
});
